<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>用代码实践浏览器的强缓存和协商缓存 | DiDi</title>
  <meta name="description" content="浏览器缓存浏览器缓存是优化性能的主要方法，也是前端面试常考的内容。当被问到什么是浏览器缓存以及分为哪些类型的时候，大多数开发者可能只会回答出“强缓存”和“协商缓存”以及它们的配置。接下来我们将用代码实践一下浏览器缓存 强缓存强缓存，顾名思义就是强制缓存。如果命中了强制缓存，它是不会向服务端发送请求的而是直接读取本地资源。我们可以通过设置HTTP的响应头来控制是否开启强缓存。值得注意的时，设置响应头">
<meta property="og:type" content="article">
<meta property="og:title" content="用代码实践浏览器的强缓存和协商缓存">
<meta property="og:url" content="https://guoyayunhappy.gitee.io/didiblog/2025/07/28/browser-cache/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="浏览器缓存浏览器缓存是优化性能的主要方法，也是前端面试常考的内容。当被问到什么是浏览器缓存以及分为哪些类型的时候，大多数开发者可能只会回答出“强缓存”和“协商缓存”以及它们的配置。接下来我们将用代码实践一下浏览器缓存 强缓存强缓存，顾名思义就是强制缓存。如果命中了强制缓存，它是不会向服务端发送请求的而是直接读取本地资源。我们可以通过设置HTTP的响应头来控制是否开启强缓存。值得注意的时，设置响应头">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/browser-cache/forceCacheFirst.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/browser-cache/forceCacheSec.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/browser-cache/forceCacheBeforeRefreshed.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/browser-cache/forceCacheAfterRefreshed.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/browser-cache/forceCacheRefreshed.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/browser-cache/negotiateCacheFirst.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/browser-cache/negotiateCacheCached.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/browser-cache/negotiateCacheRequest.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/browser-cache/negotiateCacheUpdated.png">
<meta property="article:published_time" content="2025-07-28T06:54:53.000Z">
<meta property="article:modified_time" content="2025-07-28T10:25:18.759Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="HTML">
<meta property="article:tag" content="缓存">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://guoyayunhappy.gitee.io/didiblog/images/browser-cache/forceCacheFirst.png">
  <!-- Canonical links -->
  <link rel="canonical" href="https://guoyayunhappy.gitee.io/didiblog/2025/07/28/browser-cache/index.html">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="images/favatar/idesign-logo.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/didiblog/css/style.css">

  
  
  
  
<meta name="generator" content="Hexo 7.3.0"></head>


<body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://gitee.com/GuoyayunHappy" target="_blank">
          <img class="img-circle img-rotate" src="/didiblog/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">一枚@大帅锅</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">CV工程师</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> Shanghai, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/didiblog/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/didiblog/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/didiblog/categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/didiblog/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/didiblog/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/didiblog/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://gitee.com/GuoyayunHappy" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/didiblog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>让coding更有趣!</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title">分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/JS/">JS</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/TS/">TS</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/%E7%BD%91%E7%AB%99/">网站</a><span class="category-list-count">1</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/%E7%BD%91%E7%AB%99/html/">html</a><span class="category-list-count">1</span></li></ul></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签</h3>
    <div class="widget-body">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTML/" rel="tag">HTML</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTTP/" rel="tag">HTTP</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTTPS/" rel="tag">HTTPS</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/JS/" rel="tag">JS</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/Nodejs/" rel="tag">Nodejs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/Token/" rel="tag">Token</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/cookie/" rel="tag">cookie</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/js/" rel="tag">js</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/typescript/" rel="tag">typescript</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" rel="tag">性能优化</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E7%AE%97%E6%B3%95/" rel="tag">算法</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E7%BC%93%E5%AD%98/" rel="tag">缓存</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag">设计模式</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E8%B7%A8%E5%9F%9F/" rel="tag">跨域</a><span class="tag-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/didiblog/tags/HTML/" style="font-size: 13px;">HTML</a> <a href="/didiblog/tags/HTTP/" style="font-size: 13px;">HTTP</a> <a href="/didiblog/tags/HTTPS/" style="font-size: 13px;">HTTPS</a> <a href="/didiblog/tags/JS/" style="font-size: 13px;">JS</a> <a href="/didiblog/tags/Nodejs/" style="font-size: 13px;">Nodejs</a> <a href="/didiblog/tags/Token/" style="font-size: 13px;">Token</a> <a href="/didiblog/tags/cookie/" style="font-size: 13px;">cookie</a> <a href="/didiblog/tags/js/" style="font-size: 13px;">js</a> <a href="/didiblog/tags/typescript/" style="font-size: 13px;">typescript</a> <a href="/didiblog/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" style="font-size: 13px;">性能优化</a> <a href="/didiblog/tags/%E7%AE%97%E6%B3%95/" style="font-size: 13.5px;">算法</a> <a href="/didiblog/tags/%E7%BC%93%E5%AD%98/" style="font-size: 13px;">缓存</a> <a href="/didiblog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" style="font-size: 14px;">设计模式</a> <a href="/didiblog/tags/%E8%B7%A8%E5%9F%9F/" style="font-size: 13px;">跨域</a>
    </div>
  </div>

    
      
  <div class="widget">
    <h3 class="widget-title">归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2025/07/">七月 2025</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2025/06/">六月 2025</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2024/03/">三月 2024</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2024/02/">二月 2024</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/12/">十二月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/10/">十月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/02/">二月 2023</a><span class="archive-list-count">7</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/07/28/browser-cache/" class="title">用代码实践浏览器的强缓存和协商缓存</a>
              </p>
              <p class="item-date">
                <time datetime="2025-07-28T06:54:53.000Z" itemprop="datePublished">2025-07-28</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/didiblog/categories/JS/">JS</a>
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/07/18/tail-call-optimization/" class="title">尾调用优化</a>
              </p>
              <p class="item-date">
                <time datetime="2025-07-18T11:53:08.000Z" itemprop="datePublished">2025-07-18</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/06/17/interview/" class="title">interview</a>
              </p>
              <p class="item-date">
                <time datetime="2025-06-17T03:52:38.000Z" itemprop="datePublished">2025-06-17</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2024/03/03/find-hamilton-path/" class="title">Javascript实现寻找哈密尔顿回路</a>
              </p>
              <p class="item-date">
                <time datetime="2024-03-03T00:18:45.000Z" itemprop="datePublished">2024-03-03</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2024/02/21/better-to-know-signature-and-certificate/" class="title">一文读懂加密，摘要，数字签名和证书</a>
              </p>
              <p class="item-date">
                <time datetime="2024-02-21T03:22:45.000Z" itemprop="datePublished">2024-02-21</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<main class="main" role="main">
  <div class="content">
  <article id="post-browser-cache" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      用代码实践浏览器的强缓存和协商缓存
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/didiblog/2025/07/28/browser-cache/" class="article-date">
	  <time datetime="2025-07-28T06:54:53.000Z" itemprop="datePublished">2025-07-28</time>
	</a>
</span>
        
        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/didiblog/tags/HTML/" rel="tag">HTML</a>, <a class="article-tag-link-link" href="/didiblog/tags/%E7%BC%93%E5%AD%98/" rel="tag">缓存</a>
  </span>


        

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/didiblog/2025/07/28/browser-cache/#comments" class="article-comment-link">评论</a></span>
        
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <h2 id="浏览器缓存"><a href="#浏览器缓存" class="headerlink" title="浏览器缓存"></a>浏览器缓存</h2><p>浏览器缓存是优化性能的主要方法，也是前端面试常考的内容。当被问到什么是浏览器缓存以及分为哪些类型的时候，大多数开发者可能只会回答出“强缓存”和“协商缓存”以及它们的配置。接下来我们将用代码实践一下浏览器缓存</p>
<h3 id="强缓存"><a href="#强缓存" class="headerlink" title="强缓存"></a>强缓存</h3><p>强缓存，顾名思义就是强制缓存。如果命中了强制缓存，它是不会向服务端发送请求的而是直接读取本地资源。我们可以通过设置HTTP的响应头来控制是否开启强缓存。<br>值得注意的时，设置响应头的时候，根据HTTP协议的版本有些许不同。HTTP&#x2F;1.0版本中通过设置<code>Expires</code>来控制，相当于一个时间节点。这个不在我们今天的讨论范围。HTTP&#x2F;1.1版本中通过设置<code>Cache-Control</code>来控制。这个字段包含以下常用值，他们之间可以组合使用。</p>
<ul>
<li><strong>no-store</strong>: 不缓存，从服务器获取最新资源</li>
<li><strong>no-cache</strong>: 可以缓存，但是在使用缓存前，必须向服务器验证资源是否更新，即每次请求都要和服务器协商</li>
<li><strong>public</strong>: 可以被任何缓存(包括客户端和代理服务器)，通常用于公开访问资源</li>
<li><strong>private</strong>: 只能被客户端浏览器缓存，代理服务器等中间间不能缓存该响应</li>
<li><strong>max-age</strong>: 缓存过期时间，单位秒。</li>
<li><strong>s-maxage</strong>: 仅用于共享缓存，会覆盖max-age和Expires</li>
<li><strong>must-revalidate</strong>: 必须在使用过期缓存前，向服务器验证资源是否更新</li>
<li><strong>prox-revalidate</strong>: 与must-revalidate类似，但仅针对共享缓存<br>还有一些不是很常用的值这里不一一列举了。<br>现在我们用Nodejs的express框架模拟后端服务，前端发送一个获取用户信息的请求（现实情况强缓存一般用在内容固定不常更新的文件上），这里只是一个比较好观察的例子。<br>首先我们的前端代码长这样browserCacheSample.html：<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=&quot;en&quot;&gt;</span><br><span class="line"></span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=&quot;UTF-8&quot;&gt;</span><br><span class="line">    &lt;meta name=&quot;viewport&quot; content=&quot;width=&lt;device-width&gt;, initial-scale=1.0&quot;&gt;</span><br><span class="line">    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;</span><br><span class="line">    &lt;title&gt;Document&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line"></span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;div id=&quot;myD&quot;&gt;&lt;/div&gt;</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">        &lt;div class=&quot;common&quot;&gt;这个一个模拟浏览器强缓存和协商缓存的例子&lt;/div&gt;</span><br><span class="line">        &lt;div id=&quot;myInfo&quot;&gt;个人信息：&lt;div&gt;</span><br><span class="line">                &lt;h3&gt;姓名：&lt;/h3&gt;</span><br><span class="line">                &lt;p id=&quot;userName&quot;&gt;&lt;/p&gt;</span><br><span class="line">            &lt;/div&gt;</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &lt;h3&gt;年龄：&lt;/h3&gt;</span><br><span class="line">                &lt;p id=&quot;userAge&quot;&gt;&lt;/p&gt;</span><br><span class="line">            &lt;/div&gt;</span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    const renderInfo = (data) =&gt; &#123;</span><br><span class="line">        const userNameNode = document.getElementById(&#x27;userName&#x27;);</span><br><span class="line">        const userAgeNode = document.getElementById(&#x27;userAge&#x27;);</span><br><span class="line">        userNameNode.textContent = data.name;</span><br><span class="line">        userAgeNode.textContent = data.age;</span><br><span class="line">    &#125;</span><br><span class="line">    fetch(&#x27;http://localhost:3033/getInfo&#x27;, &#123;</span><br><span class="line">        method: &quot;GET&quot;</span><br><span class="line">    &#125;).then((res) =&gt; &#123;</span><br><span class="line">        console.log(&#x27;fetch then&#x27;, res);</span><br><span class="line">        return res.json();</span><br><span class="line">    &#125;).then((data) =&gt; &#123;</span><br><span class="line">        console.log(&#x27;result is &#x27;, data);</span><br><span class="line">        renderInfo(data)</span><br><span class="line">    &#125;)</span><br><span class="line">&lt;/script&gt;</span><br><span class="line"></span><br><span class="line">&lt;/html&gt;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
下面是用Express写的一段处理前端请求的后端服务代码server.js<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">const express = require(&quot;express&quot;);</span><br><span class="line">const app = express();</span><br><span class="line">const path = require(&quot;path&quot;);</span><br><span class="line"></span><br><span class="line">app.use(express.static(path.join(__dirname, &quot;../public&quot;)));</span><br><span class="line"></span><br><span class="line">app.get(&quot;/getInfo&quot;, (req, res) =&gt; &#123;</span><br><span class="line">  res.set(&#123;</span><br><span class="line">    &quot;Cache-Control&quot;: &quot;public, max-age=60&quot;, // 1分钟缓存，max-age的单位是秒</span><br><span class="line">  &#125;);</span><br><span class="line">  res.status(200).json(&#123; name: &quot;Mary&quot;, age: 20 &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.listen(3033, () =&gt; &#123;</span><br><span class="line">  console.log(&quot;we are listen port 3033...&quot;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
然后在浏览器里我们看下长成这样：</li>
</ul>
<p><img src="/didiblog/images/browser-cache/forceCacheFirst.png" alt="image.png"><br>这里设置的缓存时间是1分钟，然后我立刻改了返回值为<code>&#123;name: &quot;Ben&quot;, age: 20&#125;</code>,重启了服务之后，刷新浏览器，发现数据也更新了, 截图如下：<br><img src="/didiblog/images/browser-cache/forceCacheSec.png" alt="image.png"></p>
<p>这就奇怪了，1分钟时间肯定没到，为啥它没有读取缓存数据而是拿到最新的数据呢，仔细观察，后来发现是浏览的的设置Disable Cache被我勾上了（上图红色圈出的地方，不确定是否是默认值），然后我就取消勾选，刷新浏览器得到了新的值，这没问题，之后我又紧接着把数据更新成了<code>&#123;name: &#39;Jacky&#39;, age: 30 &#125;</code>，再次刷新浏览器发现这次拿到的是缓存值，过了1分钟之后再刷新浏览器就拿到了最新值了。我们注意下细节，在第二次刷新浏览器拿到缓存值的network中我们可以看到那个状态码200是灰色的，而且后面的size也不是具体的文件大小，而是显示的disk cache，这就是说明这次请求没有发送到服务端而是从硬盘缓存中读取的数据。<br><span style="color:rgb(0,0,255); font-size: 18px"><strong>第一次请求</strong>:</span><br><img src="/didiblog/images/browser-cache/forceCacheBeforeRefreshed.png" alt="image.png"><br><span style="color:rgb(0,0,255); font-size: 18px"><strong>第二次拿到缓存的值</strong>：</span><br><img src="/didiblog/images/browser-cache/forceCacheAfterRefreshed.png" alt="image.png"><br><span style="color:rgb(0,0,255); font-size: 18px"><strong>第三次超过缓存时间拿到更新后的值</strong>：</span><br><img src="/didiblog/images/browser-cache/forceCacheRefreshed.png" alt="image.png"></p>
<p>看来我们设置的强缓存起作用了，接下来我们再去尝试一下协商缓存；</p>
<h3 id="协商缓存"><a href="#协商缓存" class="headerlink" title="协商缓存"></a>协商缓存</h3><p>这个协商缓存就是和服务器进行协商是用缓存值还是用最新值。协商缓存一般有2种方式去控制，当然你也可以将2者合并起来使用。 </p>
<p><strong>第一种：设置<code>ETag</code></strong>,  这个适用于对文件内容变化比较敏感但是修改不是很频繁的请求。</p>
<ul>
<li>我们在第一次响应客户端请求的时候在响应头上加一个字段<code>ETag</code>, 这个字段可以根据请求文件的内容、修改时间、版本的变动而发生变化。</li>
<li>然后客户端发起请求的时候请求头上会自动带上一个字段<code>if-none-match</code>,这个字段的值就是我们第一步设置的ETag的值(如果没更新的话)</li>
<li>然后当服务端收到客户端请求的时候我们去比较<code>ETag</code>和<code>if-none-match</code>这两个值，如果相等则让它取缓存值，否则返回最新值<br><strong>第二种：设置<code>Last-Modified</code></strong>, 其实和第一种一样，不过适用场景不一样；这个适用于对文件修改比较频繁的请求。因为这个精度只到秒。</li>
<li>第一步也是在响应头上设置一个字段<code>Last-Modified</code>,这个值一般就是取文件的最后修改日期</li>
<li>然后客户端发起请求的时候请求头上会自动带上一个字段<code>if-modified-since</code>,这个字段的值就是我们第一步设置的<code>Last-Modified</code>的值(如果没更新的话)</li>
<li>然后当服务端收到客户端请求的时候我们去比较<code>Last-Modified</code>和<code>if-modified-since</code>这两个值，如果相等则让它取缓存值，否则返回最新值</li>
</ul>
<p>这两种方案看起来差不多（其实我也觉得差不多），大家需要记住的是两者之间的匹配关系：<br>服务端 ETag &lt;&#x3D;&gt; 客户端 if-none-match<br>服务端 Last-Modified &lt;&#x3D;&gt; 客户端 if-modified-since<br>网上有些使用建议，我这里抄过来了，大家可以看看：</p>
<blockquote>
<p>静态资源：对于图片、CSS、JavaScript 等静态资源，可同时设置 Last-Modified 和 ETag。这样即使 Last-Modified 因时间精度或元数据变化有误判，ETag 也能准确判断资源是否更新。<br>动态资源：若资源频繁变化且对性能要求较高，可只使用 Last-Modified 以减少服务器计算 ETag 的开销；若对资源变化准确性要求极高，则使用 ETag 或两者结合。</p>
</blockquote>
<p>下面我们用实际代码来模拟一下协商缓存，我们还是用同样一份前端代码(上文中的browserCacheSample.html)<br>然后这里返回的内容我放到了一个example.json文件里，如果这个文件没有改动，那就使用缓存值，否则就返回最新值。<br>这里我是基于文件的内容创建的<code>ETag</code>值.</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">const express = require(&quot;express&quot;);</span><br><span class="line">const app = express();</span><br><span class="line">const path = require(&quot;path&quot;);</span><br><span class="line">const crypto = require(&quot;crypto&quot;);</span><br><span class="line">const fs = require(&quot;fs&quot;);</span><br><span class="line"></span><br><span class="line">app.use(express.static(path.join(__dirname, &quot;../public&quot;)));</span><br><span class="line">app.get(&quot;/getInfo&quot;, (req, res) =&gt; &#123;</span><br><span class="line">  // 读取文件内容</span><br><span class="line">  fs.readFile(</span><br><span class="line">    path.resolve(__dirname, &quot;../public/example.json&quot;),</span><br><span class="line">    &quot;utf-8&quot;,</span><br><span class="line">    (err, data) =&gt; &#123;</span><br><span class="line">      if (err) &#123;</span><br><span class="line">        res.status(500).send(&quot;Server error&quot;);</span><br><span class="line">        return;</span><br><span class="line">      &#125;</span><br><span class="line">      const ifNoneMatch = req.headers[&quot;if-none-match&quot;];</span><br><span class="line">      // 计算文件内容的 MD5 哈希值</span><br><span class="line">      const etag = crypto.createHash(&quot;md5&quot;).update(data).digest(&quot;hex&quot;);</span><br><span class="line">      console.log(&quot;request header&quot;, req.headers);</span><br><span class="line">      if (ifNoneMatch === etag) &#123;</span><br><span class="line">        res.status(304).end();</span><br><span class="line">      &#125; else &#123;</span><br><span class="line">        res.set(&#123;</span><br><span class="line">          &quot;Cache-Control&quot;: &quot;no-cache&quot;,</span><br><span class="line">          ETag: etag,</span><br><span class="line">        &#125;);</span><br><span class="line">        res.status(200).json(JSON.parse(data));</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.listen(3033, () =&gt; &#123;</span><br><span class="line">  console.log(&quot;we are listen port 3033...&quot;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><strong>用来模拟返回值的example.json文件</strong>：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    &quot;name&quot;: &quot;Stephen&quot;,</span><br><span class="line">    &quot;age&quot;: 30</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接下来我们再看下这次的结果，在第二次拿到缓存值后，我们改动了example.json文件,最后一次拿到了更新的数据。<br><span style="color:rgb(0,0,255); font-size: 18px"><strong>第一次请求</strong>:</span><br><img src="/didiblog/images/browser-cache/negotiateCacheFirst.png" alt="image.png"><br><span style="color:rgb(0,0,255); font-size: 18px"><strong>第二次拿到缓存的值</strong>：</span><br><img src="/didiblog/images/browser-cache/negotiateCacheCached.png" alt="image.png"><br><img src="/didiblog/images/browser-cache/negotiateCacheRequest.png" alt="image.png"><br><span style="color:rgb(0,0,255); font-size: 18px"><strong>第三次拿到文件改动后的值</strong>：</span><br><img src="/didiblog/images/browser-cache/negotiateCacheUpdated.png" alt="image.png"></p>
<p>我们注意到的是第二次请求的状态码是<strong>304</strong>而非<strong>200</strong>，说明我们返回的是缓存值而不是最新值,那么协商缓存也是成功模拟的。但这里也有些缺陷，就是每次请求的时候我都要去读取一下文件内容去计算新的ETag值来比较，也是比较耗性能的。我们也可以用<code>Last-Modified</code>字段做比较，这样就可以不用计算hash了。<br>下面是我用<code>Last-Modified</code>字段模拟协商缓存的例子，结果也是好的，这里我就不贴截图了。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">const express = require(&quot;express&quot;);</span><br><span class="line">const app = express();</span><br><span class="line">const path = require(&quot;path&quot;);</span><br><span class="line">const crypto = require(&quot;crypto&quot;);</span><br><span class="line">const fs = require(&quot;fs&quot;);</span><br><span class="line"></span><br><span class="line">app.use(express.static(path.join(__dirname, &quot;../public&quot;)));</span><br><span class="line">const getFileContent = () =&gt; &#123;</span><br><span class="line">  return (result = fs.readFileSync(</span><br><span class="line">    path.resolve(__dirname, &quot;../public/example.json&quot;),</span><br><span class="line">    &quot;utf-8&quot;</span><br><span class="line">  ));</span><br><span class="line">&#125;;</span><br><span class="line">app.get(&quot;/getInfo&quot;, (req, res) =&gt; &#123;</span><br><span class="line">  // 获取文件最后修改时间</span><br><span class="line">  fs.stat(</span><br><span class="line">    path.resolve(__dirname, &quot;../public/example.json&quot;),</span><br><span class="line">    async (statErr, stats) =&gt; &#123;</span><br><span class="line">      if (statErr) &#123;</span><br><span class="line">        res.status(500).send(&quot;Server error&quot;);</span><br><span class="line">        return;</span><br><span class="line">      &#125;</span><br><span class="line">      const lastModified = stats.mtime.toUTCString();</span><br><span class="line">      const ifModifiedSince = req.headers[&quot;if-modified-since&quot;];</span><br><span class="line"></span><br><span class="line">      if (ifModifiedSince &amp;&amp; ifModifiedSince === lastModified) &#123;</span><br><span class="line">        res.status(304).end();</span><br><span class="line">      &#125; else &#123;</span><br><span class="line">        res.set(&#123;</span><br><span class="line">          &quot;Cache-Control&quot;: &quot;no-cache&quot;,</span><br><span class="line">          &quot;Last-Modified&quot;: lastModified,</span><br><span class="line">        &#125;);</span><br><span class="line">        const result = getFileContent();</span><br><span class="line">        res.status(200).json(JSON.parse(result));</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.listen(3033, () =&gt; &#123;</span><br><span class="line">  console.log(&quot;we are listen port 3033...&quot;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>还是那句话，纸上得来终觉浅，绝知此事要躬行。再多理论也低不是实践来的记忆深刻。</p>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://guoyayunhappy.gitee.io/didiblog/2025/07/28/browser-cache/" title="用代码实践浏览器的强缓存和协商缓存" target="_blank" rel="external">https://guoyayunhappy.gitee.io/didiblog/2025/07/28/browser-cache/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/GuoyayunHappy" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/didiblog/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/GuoyayunHappy" target="_blank"><span class="text-dark">一枚@大帅锅</span><small class="ml-1x">CV工程师</small></a></h3>
        <div>个人简介。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    
    <li class="next">
      <a href="/didiblog/2025/07/18/tail-call-optimization/" title="尾调用优化"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
  </ul>
  
  
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-fancy btn-donate pop-onhover bg-gradient-warning" data-toggle="modal" data-target="#donateModal"><span>赏</span></button>
  <!-- <div class="wave-icon wave-icon-danger btn-donate" data-toggle="modal" data-target="#donateModal">
    <div class="wave-circle"><span class="icon"><i class="icon icon-bill"></i></span></div>
  </div> -->
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  
<!-- Modal -->
<div class="modal modal-center modal-small modal-xs-full fade" id="donateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content donate">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <div class="modal-body">
        <div class="donate-box">
          <div class="donate-head">
            <p>感谢您的支持，我会继续努力的!</p>
          </div>
          <div class="tab-content">
            <div role="tabpanel" class="tab-pane fade active in" id="alipay">
              <div class="donate-payimg">
                <img src="/didiblog/images/donate/alipayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开支付宝扫一扫，即可进行扫码打赏哦</p>
            </div>
            <div role="tabpanel" class="tab-pane fade" id="wechatpay">
              <div class="donate-payimg">
                <img src="/didiblog/images/donate/wechatpayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开微信扫一扫，即可进行扫码打赏哦</p>
            </div>
          </div>
          <div class="donate-footer">
            <ul class="nav nav-tabs nav-justified" role="tablist">
              <li role="presentation" class="active">
                <a href="#alipay" id="alipay-tab" role="tab" data-toggle="tab" aria-controls="alipay" aria-expanded="true"><i class="icon icon-alipay"></i> 支付宝</a>
              </li>
              <li role="presentation" class="">
                <a href="#wechatpay" role="tab" id="wechatpay-tab" data-toggle="tab" aria-controls="wechatpay" aria-expanded="false"><i class="icon icon-wepay"></i> 微信支付</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>



</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://gitee.com/GuoyayunHappy" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/didiblog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/didiblog/js/plugin.min.js"></script>


<script src="/didiblog/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/didiblog/',
        CONTENT_URL: '/didiblog/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/didiblog/js/insight.js"></script>






   




   
    
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/valine"></script>
  <script type="text/javascript">
  var GUEST = ['nick', 'mail', 'link'];
  var meta = 'nick,mail,link';
  meta = meta.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#vcomments',
    verify: false,
    notify: false,
    appId: '',
    appKey: '',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: meta,
    pageSize: '10' || 10,
    visitor: false
  });
  </script>

     







</body>
</html>